package com.zsr.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsr.eduservice.entity.EduChapter;
import com.zsr.eduservice.entity.EduVideo;
import com.zsr.eduservice.entity.vo.ChapterVo;
import com.zsr.eduservice.entity.vo.VideoVo;
import com.zsr.eduservice.mapper.EduChapterMapper;
import com.zsr.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsr.eduservice.service.EduVideoService;
import com.zsr.servicebase.exceptionhandler.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zsr
 * @since 2021-06-11
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;


    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        //1. 根据课程id查询课程里所有的章节
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id", courseId);
        chapterWrapper.orderByAsc("sort");
        List<EduChapter> chapters = this.list(chapterWrapper);

        //2. 根据课程id查询所有小节
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        List<EduVideo> videos = eduVideoService.list(videoWrapper);

        return chapters.stream().map(a -> new ChapterVo(
                a.getId()
                , a.getTitle()
                , videos.stream().filter(b -> b.getChapterId().equals(a.getId()))
                .map(c -> new VideoVo(
                        c.getId()
                        , c.getTitle()
                        , c.getIsFree()
                        , c.getVideoSourceId())).collect(Collectors.toList())))
                .collect(Collectors.toList());

    }

    @Override
    public boolean removeChapterById(String id) {
        //根据id查询是否存在视频，如果有则提示用户尚有子节点
        if (eduVideoService.getCountByChapterId(id)) throw new BusinessException(20001, "该分章节下存在视频课程，请先删除视频课程");
        //大于0删除成功
        Integer result = baseMapper.deleteById(id);
        return null != result && result > 0;
    }

    @Override
    public void removeChapterByCourseId(String courseId) {
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id",courseId);
        this.remove(chapterWrapper);
    }
}
